package com.chenjiajin.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.read.metadata.ReadSheet;
import com.chenjiajin.listener.ExcelExportDataListener;
import com.chenjiajin.domain.DemoImport;
import com.chenjiajin.service.TestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;

/**
 * 简单入门
 */
@RestController
public class DemoController {

    @Autowired
    private TestService service;


    @RequestMapping("/aop")
    public String aop() {
        System.out.println("这是执行方法");
        return "success";
    }

    //导入
    @PostMapping("/easyExcel")
    public String aa(@RequestParam("file") MultipartFile file) throws IOException {
        if (file == null || file.getSize() == 0) {
            throw new RuntimeException("导入的文件为空 !");
        }

        // 获取输入流
        InputStream input = file.getInputStream();

        // 构造监听器
        AnalysisEventListener<DemoImport> listener = new ExcelExportDataListener(service);

        // 自定义监听规则
        ExcelReader excelReader =
                EasyExcel
                        .read(input, DemoImport.class, listener)
                        .headRowNumber(1)  //表示第1行开始读
                        .build();

        ReadSheet readSheet =
                EasyExcel
                        .readSheet(0)
                        .build();

        try {
            excelReader.read(readSheet);
        } catch (Exception e) {
            e.printStackTrace();
            String sheetName = readSheet.getSheetName();
            Integer sheetNo = readSheet.getSheetNo();
            System.out.println("在第" + sheetNo + "行的第" + sheetName + "列的输入格式有误 ！");
        } finally {
            excelReader.finish();      // 这里千万别忘记关闭，读的时候会创建临时文件，到时磁盘会崩的
        }

        return "success";
    }

    //导出
    //  http://localhost/bb
    @GetMapping("/bb")
    public void bb(HttpServletResponse response) throws IOException, URISyntaxException {
        service.bb(response);
    }


}